package org.example.controller.platform;

import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.common.result.Result;
import org.example.common.utils.SaTokenUtils;
import org.example.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 平台端认证控制器
 */
@RestController
@RequestMapping("/platform/auth")
@Slf4j
@Component("platformAuthController")
@Tag(name = "平台端-认证", description = "平台端认证相关接口")
@SecurityRequirement(name = "platformBearerAuth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private SaTokenUtils saTokenUtils;

    /**
     * 平台端登录接口
     * 路径：/api/platform/auth/login
     */
    @PostMapping("/login")
    @io.swagger.v3.oas.annotations.Operation(summary = "平台端登录", description = "使用手机号和验证码进行平台端登录")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        try {
            String phone = loginRequest.get("phone");
            String verificationCode = loginRequest.get("verificationCode");
            
            // 验证参数
            if (phone == null || verificationCode == null) {
                return Result.badRequest("手机号和验证码不能为空");
            }
            
            // 调用认证服务
            Map<String, Object> loginResult = authService.platformLogin(phone, verificationCode);
            
            // 构建符合API文档的响应结构
            Map<String, Object> responseData = buildLoginResponse(loginResult);
            
            return Result.success("登录成功", responseData);
            
        } catch (Exception e) {
            log.error("平台端登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        try {
            try {
                Long userId = saTokenUtils.getCurrentUserId();
                String sessionId = saTokenUtils.getSessionId();
                org.example.service.LoginLogService loginLogService = org.springframework.web.context.ContextLoader.getCurrentWebApplicationContext().getBean(org.example.service.LoginLogService.class);
                if (userId != null && sessionId != null) {
                    loginLogService.recordLogout(userId, sessionId);
                }
            } catch (Exception ignore) {}
            saTokenUtils.logout();
            return Result.success("退出登录成功");
        } catch (Exception e) {
            log.error("退出登录失败", e);
            return Result.error("退出登录失败：" + e.getMessage());
        }
    }

    /**
     * 构建登录响应数据结构
     * 符合API文档要求
     */
    private Map<String, Object> buildLoginResponse(Map<String, Object> loginResult) {
        // TODO: 根据实际的登录结果构建响应数据
        // 这里需要根据你的AuthService返回的数据结构来完善
        
        Map<String, Object> responseData = new HashMap<>();
        
        // 基础信息
        responseData.put("token", loginResult.get("token"));
        responseData.put("userInfo", loginResult.get("userInfo"));
        
        // 权限信息
        responseData.put("permissions", loginResult.get("permissions"));
        responseData.put("permissionMap", loginResult.get("permissionMap"));
        
        // 租户信息（平台端可能不需要，但API文档中有）
        responseData.put("currentCompany", loginResult.get("currentCompany"));
        responseData.put("availableCompanies", loginResult.get("availableCompanies"));

        // Token 过期信息
        responseData.put("expiresAt", loginResult.get("expiresAt"));
        responseData.put("expiresIn", loginResult.get("expiresIn"));
        
        return responseData;
    }
}
